package com.jiliang.member.service.impl;

import com.jiliang.auth.dao.mapper.AuthRoleMemberExMapper;
import com.jiliang.common.bean.BeanCopierDsUtil;
import com.jiliang.common.bean.BeanCopyDsUtil;
import com.jiliang.common.exception.Errors;
import com.jiliang.common.exception.business.ServerServiceException;
import com.jiliang.common.utils.BoIdGenerator;
import com.jiliang.common.utils.PasswordUtil;
import com.jiliang.member.dto.MemberIndexVo;
import com.jiliang.member.dto.MemberInfoDTO;
import com.jiliang.member.dto.MemberInfoVo;
import com.jiliang.member.dto.SystemAuthBo;
import com.jiliang.member.entity.*;
import com.jiliang.member.mapper.MemberInfoMapper;
import com.jiliang.member.mapper.MemberLoginMapper;
import com.jiliang.member.mapper.MemberMenuExMapper;
import com.jiliang.member.mapper.MemberMenuMapper;
import com.jiliang.member.service.MemberInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Log4j2
@Service
public class MemberInfoServiceImpl implements MemberInfoService {

    @Autowired
    private MemberInfoMapper memberInfoMapper;

    @Autowired
    private MemberLoginMapper memberLoginMapper;
    @Resource private MemberMenuMapper memberMenuMapper;
    @Resource private MemberMenuExMapper memberMenuExMapper;
    @Resource
    private AuthRoleMemberExMapper authRoleMemberExMapper;

    @Value("${pageSize}")
    private Integer pageSize;

    @Override
    public int addMemberInfo(MemberInfoDTO dto) {
        MemberInfo memberInfo = new MemberInfo();
        BeanCopyDsUtil.copyProperties(dto, memberInfo);
        //生成随机的bo_id
        long l = BoIdGenerator.generateBoId();
        memberInfo.setBoId(l+"");
        //查询用户是否存在
        int j = selectMemberInfoByLoginName(dto.getLoginName());
        if (j > 0){
            return 0;
        }

        //插入用户信息数据库
        int i = memberInfoMapper.insertSelective(memberInfo);

        //拿到信息添加到用户登录表中
        MemberLogin memberLogin = new MemberLogin();
        memberLogin.setBoId(l+"");
        memberLogin.setLoginName(dto.getLoginName());
        //默认密码-后续更改
        memberLogin.setLoginPwd(PasswordUtil.encryptPasswordWithSalt("123456"));
        memberLoginMapper.insertSelective(memberLogin);

        for (MemberMenu mm : dto.getMemberMenus()) {
            try {
                mm.setBoId(String.valueOf(l));
                mm.setCreateTime(new Date());
                memberMenuMapper.insertSelective(mm);
            } catch (Exception e) {
                log.error("新增用户: 系统关联关系新增失败");
                throw new ServerServiceException(Errors.SYSTEM_INSERT_ERROR, "用户菜单关系新增失败");
            }
        }
        return i;
    }

    /**
     * @param boId
     * @param sysId
     */
    private void addMemberSystem(String boId, Integer sysId) {
        if (memberMenuExMapper.selHasSub(sysId)) {
            List<Integer> idList = memberMenuExMapper.selIdListByParentId(sysId);
            for (Integer id : idList) {
                MemberMenu memberSystem = new MemberMenu(boId, id, new Date());
                memberMenuMapper.insertSelective(memberSystem);
            }
        } else {
            MemberMenu memberSystem = new MemberMenu(boId, sysId, new Date());
            memberMenuMapper.insertSelective(memberSystem);
        }
    }

    @Override
    public int updateMemberInfo(MemberInfoDTO dto) {
        //更新用户信息数据库
        int i = memberInfoMapper.updateByPrimaryKeySelective(dto);
        //更新用户应用关系
        //先删除原有关系
        MemberMenuExample example = new MemberMenuExample();
        example.createCriteria().andBoIdEqualTo(dto.getBoId());
        memberMenuMapper.deleteByExample(example);
        //再添加新关系
        for (MemberMenu mm : dto.getMemberMenus()) {
            try {
                mm.setBoId(dto.getBoId());
                mm.setCreateTime(new Date());
                memberMenuMapper.insertSelective(mm);
            } catch (Exception e) {
                log.error("新增用户: 系统关联关系新增失败");
                throw new ServerServiceException(Errors.SYSTEM_INSERT_ERROR, "用户菜单关系新增失败");
            }
        }
        return i;
    }

    @Override
    public int deleteMemberInfo(String id) {
        //删除用户信息数据库
        MemberInfo memberInfo = new MemberInfo();
        memberInfo.setBoId(id);
        memberInfo.setIsEnabled((short)0);
        int i = memberInfoMapper.updateByPrimaryKeySelective(memberInfo);
        //删除用户登录信息
        MemberLogin memberLogin = new MemberLogin();
        memberLogin.setBoId(id);
        memberLogin.setIsEnabled((short)0);
        int j = memberLoginMapper.updateByPrimaryKeySelective(memberLogin);
        //删除用户相关角色信息
        authRoleMemberExMapper.deleteRoleMember(id);
        if (i > 0 && j > 0) {
            return 1;
        }
        return 0;
    }

    @Override
    public List<MemberInfo> selectMemberInfoList(MemberInfoDTO dto) {
        if (dto == null){
            MemberInfoExample example = new MemberInfoExample();
            MemberInfoExample.Criteria criteria = example.createCriteria();
            criteria.andIsEnabledEqualTo((short)1);
            return memberInfoMapper.selectByExample(example);
        }
        MemberInfoExample example = new MemberInfoExample();
        MemberInfoExample.Criteria criteria = example.createCriteria();
        if (dto.getUserName() != null && !"".equals(dto.getUserName())){
            criteria.andUserNameLike("%"+dto.getUserName()+"%");
        }
        if (dto.getcId() != null && !"".equals(dto.getcId())) {
            criteria.andCIdEqualTo(dto.getcId());
        }
        if (dto.getdId() != null && !dto.getdId().equals("")) {
            criteria.andDIdEqualTo(dto.getdId());
        }
        if (dto.getJobId() != null && !dto.getJobId().equals("")) {
            criteria.andJobIdLike("%"+dto.getJobId()+"%");
        }
        criteria.andIsEnabledEqualTo((short)1);
        return memberInfoMapper.selectByExample(example);
    }

    @Override
    public PageInfo selectMemberInfoListByPage(MemberInfoDTO dto) {
        Integer pageNum = 1;
        if (dto != null && dto.getPageNum() != null){
            pageNum = dto.getPageNum();
        }
        Integer pageSize = this.pageSize;
        if (dto != null && dto.getPageSize() != null){
            pageSize = dto.getPageSize();
        }
        PageHelper.startPage(pageNum,pageSize);
        return new PageInfo(this.selectMemberInfoList(dto));
    }

    @Override
    public int freezeMemberInfo(MemberInfoDTO dto) {
        MemberInfo memberInfo = new MemberInfo();
        BeanCopyDsUtil.copyProperties(dto, memberInfo);
        //冻结或解冻用户信息
        memberInfoMapper.updateByPrimaryKeySelective(memberInfo);
        //冻结用户登录信息
        MemberLogin memberLogin = new MemberLogin();
        memberLogin.setBoId(memberInfo.getBoId());
        memberLogin.setStatus(memberInfo.getUserStatus());
        memberLoginMapper.updateByPrimaryKeySelective(memberLogin);
        //冻结用户相关角色信息
        authRoleMemberExMapper.freezeRoleMember(memberInfo.getBoId(), memberInfo.getUserStatus());
        return 0;
    }

    @Override
    public MemberInfo selectMemberInfoById(String id) {
        return memberInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public int selectCountByParams(Integer menuId, String cName, String dName) {
        return memberMenuExMapper.selectCountByParams(menuId, cName, dName);
    }

    @Override
    public List<Map> selectDeptByCompany(MemberInfo memberInfo) {
        //根据用户所属部门查询所在公司id
        String companyId = memberInfoMapper.selectUserCompany(memberInfo.getdId());
        //根据公司查询所有部门
        List<Map> maps = memberInfoMapper.selectDeptByCompany(companyId);
        return maps;
    }

    @Override
    public MemberIndexVo selMemberIndexById(String id) {
        MemberInfo memberInfo = memberInfoMapper.selectByPrimaryKey(id);
        MemberInfoVo vo = BeanCopierDsUtil.copyProperties(memberInfo, MemberInfoVo.class);
        MemberMenuExample example = new MemberMenuExample();
        example.createCriteria().andBoIdEqualTo(id);
        List<MemberMenu> memberMenuList = memberMenuMapper.selectByExample(example);
        List<SystemAuthBo> boList = BeanCopierDsUtil.copyPropertiesOfList(memberMenuList, SystemAuthBo.class);
        return new MemberIndexVo(vo, boList);
    }

    /**
     * 根据用户名查询用户信息
     * @param loginName
     * @return
     */
    public int selectMemberInfoByLoginName(String loginName) {
        MemberLoginExample example = new MemberLoginExample();
        MemberLoginExample.Criteria criteria = example.createCriteria();
        criteria.andLoginNameEqualTo(loginName);
        List<MemberLogin> memberLoginList = memberLoginMapper.selectByExample(example);
        if (memberLoginList.size() > 0) {
            return 1;
        }
        return 0;
    }
}
